from django.shortcuts import render, redirect, get_object_or_404

from .models import Contact


# Create your views here.
def index(request):
    contact_list = Contact.objects.order_by("-pub_date").all()
    return render(request, 'contact/index.html', {'contact_list': contact_list})

def detail(request, contact_id):
    contact = Contact.objects.get(pk=contact_id)
    return render(request, 'contact/detail.html', {'contact': contact})

def add_contact(request):
    context = {}
    if request.method == 'POST':
        name = request.POST.get('name')
        gender = request.POST.get('gender')
        phone = request.POST.get('phone')
        pub_date = request.POST.get('pub_date')

        person = Contact(name=name, gender=gender, phone=phone, pub_date=pub_date)
        person.save()
        return redirect("contact:index")

    return render(request, 'contact/index.html', context)

def delete_contact(request, contact_id):
    contact = Contact.objects.get(pk=contact_id)
    contact.delete()
    return redirect("contact:index")

def edit_info(request, contact_id):
    contact = Contact.objects.get(pk=contact_id)
    return render(request, 'contact/edit_info.html', {'contact': contact})

def edit_contact(request, contact_id):
    person = get_object_or_404(Contact, pk=contact_id)
    if request.method == 'POST':
        person.name = request.POST.get('name')
        person.gender = request.POST.get('gender')
        person.phone = request.POST.get('phone')
        # pub_date = request.POST.get('pub_date')
        # person = Contact(name=name, gender=gender, phone=phone, pub_date=pub_date)
        # person = Contact(name=name, gender=gender, phone=phone)
        person.save()
        return redirect("contact:detail", contact_id)
    return render(request, 'contact/detail.html', {'contact': contact})

def search_contact(request):
    contact = {}
    if request.method == 'GET':
        name = request.GET.get('name')
        try:
            contact = Contact.objects.get(name=name)
        except Contact.DoesNotExist:
            contact = {}
        return render(request, 'contact/detail.html', {'contact': contact})
